package net.jcip.examples.vehicles;

import net.jcip.examples.vehicles.point.ImmutablePoint;
import net.jcip.examples.vehicles.point.Point;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class DelegatingVehicleTracker {

    private final ConcurrentMap<String, ImmutablePoint> locations;
    private final Map<String, ImmutablePoint> unmodifiableMap;

    public DelegatingVehicleTracker(Map<String, Point> points) {
        locations = new ConcurrentHashMap<String, ImmutablePoint>();
        for (String key : points.keySet()) {
            locations.put(key, new ImmutablePoint(locations.get(key)));
        }
        unmodifiableMap = Collections.unmodifiableMap(locations);
    }

    private Point safeGet(String name) {
        Point loc = locations.get(name);
        if (loc == null)
            throw new IllegalArgumentException("No such ID: " + name);
        return loc;
    }

    public Point getLocation(String name) {
        return safeGet(name);
    }

    public void setLocation(String name, Point point) {
        if (locations.replace(name, new ImmutablePoint(point.getX(), point.getY())) == null) {
            throw new IllegalArgumentException("No such ID: " + name);
        }
    }

    public Map<String, ImmutablePoint> getLocations() {
        return unmodifiableMap;
    }

    public Map<String, ImmutablePoint> getLocationsAsStatic() {
        return Collections.unmodifiableMap(new HashMap<String, ImmutablePoint>(locations));
    }

}
